import { Image, Input, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { Component } from 'react';

import * as T from '../types';
import '../css/store.less';
import '../css/index.less';
import actions from '../actions/index';
import { connect } from 'react-redux';
import { store2Props } from '../selectors';
import PictureCom from './picture-com';
import Enclosure from './enclosure';

import Price from '@/pages/common/goods/price';
import plus from '../img/plus.png';
import { WMkit, immutable } from 'wmkit';

const noneImg = require('../img/none.png');

import arrow from '@/assets/image/common/arrow.png';
import InvoiceIcon from '@/assets/image/common/remind.png';

type IStoreItemProps = T.IProps & T.IStoreItemProps;

const TYPES = {
  '0': '满减优惠',
  '1': '满折优惠',
  '2': '满赠优惠',
};

const INVOICE_TYPE = {
  '0': '不支持开票',
  '1': '不需要发票',
  '2': '普通发票',
  '3': '增值税发票',
};

const MARKETING_TYPE = {
  0: '满减',
  1: '满折',
  2: '满赠',
  3: '一口价优惠',
  4: '第二件半价',
  5: '秒杀',
  6: '组合套餐',
};

@connect<Partial<IStoreItemProps>, T.IStoreItemState>(store2Props, actions)
export default class Store extends Component<Partial<IStoreItemProps>, T.IStoreItemState> {
  constructor(props: IStoreItemProps) {
    super(props);
  }

  render() {
    let {
      actions: { action },
      actions,
      myStore = {},
      main,
    } = this.props;
    const { orderList, stores = [], isBookingSaleGoods, shopName, inviteeName, purchaseBuy, isRecharge, rechargeInfo, virtualGoods } = main || {};
    const { invoiceData, buyRemark, enclosures } = orderList || {};
    const { supplier, tradeItems, gifts, tradeConfirmMarketingList } = myStore;
    gifts.forEach((gift) => {
      gift.isGift = true;
    });
    const allSkus = tradeItems.concat(gifts);

    const cartList = allSkus
      .filter((sku, index) => index < 4)
      .map((sku) => {
        return {
          url: sku.pic,
        };
      });
    const { discountsPrice, tradePrice } = myStore;

    const prices = (immutable.fromJS(discountsPrice) || immutable.fromJS([]))
      .groupBy((item) => item.get('type'))
      .toArray();
    const invoiceType = invoiceData && invoiceData[supplier.supplierId]['supportInvoice'];
    const enclosureList = enclosures && enclosures[supplier.storeId];

    let initGiftMarketLevelId;
    tradeItems.forEach((item) => {
      if (item.marketingLevelIds) {
        initGiftMarketLevelId = item.marketingLevelIds[0];
      }
    });
    return (
      <>
        <View className="confirm-store">
          {isRecharge && (
            <View className='recharge-box'>
              <Text className='recharge-title'>充值号码</Text>
              <Input
                type='text'
                className='recharge-text'
                placeholder={rechargeInfo}
                onInput={(e) => action.commonChange('main.chargeAccount', e.detail.value)}
              />
              <View className="invoice-header">
                <Image className="invoice-icon" src={InvoiceIcon} />
                <Text className="invoice-tips" decode={true}>
                  购买须知：请仔细核对充值账号，确保账号准确性。虚拟商品不支持退货
                </Text>
              </View>
            </View>
          )}
          <View className="confirm-store-left">
            {/*{WMkit.isShop() ? (*/}
            {/*  <View*/}
            {/*    onClick={() => {*/}
            {/*      Taro.navigateTo({*/}
            {/*        url: `/pages/package-B/distribution/store/social-c/shop-index-c/index?inviteeId=${WMkit.inviteeId()}`,*/}
            {/*      });*/}
            {/*    }}*/}
            {/*  >*/}
            {/*    <Text className="confirm-store-name">*/}
            {/*      {inviteeName}的{shopName}*/}
            {/*    </Text>*/}
            {/*  </View>*/}
            {/*) : (*/}
            {/*  <View style={{flexDirection: 'row'}}>*/}
            {/*    {supplier.isSelf && (*/}
            {/*      <View className="confirm-store-type">*/}
            {/*        <Text className="confirm-store-type-text">自营</Text>*/}
            {/*      </View>*/}
            {/*    )}*/}
            {/*    <Text className="confirm-store-name">{supplier.storeName}</Text>*/}
            {/*  </View>*/}
            {/*)}*/}
          </View>
          {tradeConfirmMarketingList?.length > 0 && purchaseBuy && (
            <View className="marketing-box">
              {this._distinct(tradeConfirmMarketingList).map((item, index) => {
                return (
                  item && (
                    <View className="marketing" key={index} style={{ justifyContent: 'flex-start' }}>
                      <View className="act-type">
                        <Text className="act-type-label">
                          {item.marketingType == 4 ? item.marketingDesc.substr(4) : MARKETING_TYPE[item.marketingType]}
                        </Text>
                      </View>
                      <Text className="act-content">{item.marketingDesc}</Text>

                      {item.marketingType == 2 && (
                        //领取赠品 满赠显示
                        <View
                          className="go-invalid"
                          onClick={async () => {
                            await action._getMarketingById(item);
                            await action.commonChange([
                              { paths: 'main.initGiftMarketLevelId', value: initGiftMarketLevelId },
                            ]);
                            await action.commonChange([{ paths: 'main.gifts.isMaskOpen', value: true }]);
                          }}
                        >
                          <Text className="coupon-text">领取赠品</Text>
                        </View>
                      )}
                    </View>
                  )
                );
              })}
            </View>
          )}

          {/* 只有一个店铺显示明细,只有一个店铺跳转到商品详情页，不跳转到清单页 */}
          {stores && stores.length == 1 ? (
            <View
              className="order-confirm-middle-detail"
              style={tradeConfirmMarketingList?.length > 0 ? { paddingTop: '20px' } : { paddingTop: '10px' }}
            >
              {allSkus
                ? allSkus.map((item, index) => {
                  return (
                    <View
                      key={index}
                      className="product-item"
                      onClick={async () => {
                        await action._urlChange(5, item);
                      }}
                    >
                      <Image className="img-item" key={item.oid} src={item.pic ? item.pic : noneImg} />
                      <View className="good-info">
                        <View className="good-info-detail">
                          {item.isGift && (
                            <View className="gift-sku-icon">
                              <Text className="gift-sku-text">赠品</Text>
                            </View>
                          )}
                          <View className="name">{item.skuName ? item.skuName : '-'}</View>
                          <View className="specDetails">{item.specDetails ? item.specDetails : ''}</View>
                        </View>
                        <View className="right">
                          <View className="price">
                            <Price price={item.isGift ? 0 : item.price} buyPoint={item.buyPoint} />
                          </View>
                          <View className="number">{'x' + item.num}</View>
                        </View>
                      </View>
                    </View>
                  );
                })
                : null}
            </View>
          ) : (
            <View
              className="order-confirm-store-item"
              onClick={async () => {
                await action._urlChange(3, supplier.storeId);
              }}
              style={{ marginTop: '10px' }}
            >
              <View className="sku-pic-list">
                {cartList.slice(0, 4).map((item, index) => (
                  <PictureCom key={index} type={0} url={item.url} />
                ))}
              </View>
              <View className="store-item-right">
                <Text className="item-text">{allSkus.length}</Text>
                <Image className="arrow-img" src={arrow} />
              </View>
            </View>
          )}

          <View
            className="order-confirm-store-item"
            onClick={async () => {
              invoiceType && (await action._urlChange(2, supplier.supplierId));
            }}
          >
            <Text className="order-item-label">发票信息</Text>
            <View className="store-item-right">
              <Text className="item-text">{INVOICE_TYPE[invoiceType]}</Text>
              {invoiceType !== 0 && <Image className="arrow-img" src={arrow} />}
            </View>
          </View>

          {!virtualGoods && (
            <>
              <View className="order-confirm-store-item">
                <Text className="order-item-label">订单备注</Text>

                <View className="order-item-input">
                  <Input
                    maxlength={100}
                    value={buyRemark[supplier.storeId]}
                    placeholder="点击输入，100字以内"
                    placeholderStyle="color:#00000066"
                    className="invoice-input"
                    onInput={(e) => {
                      action._orderBuyRemarkChange(supplier.storeId, e.detail.value);
                    }}
                  />
                </View>
              </View>

              <View
                className="order-confirm-store-item"
                onClick={async () => {
                  this.listenKeyBordHidden(enclosures, supplier);
                }}
              >
                <Text className="order-item-label">订单附件</Text>
                <View className="store-item-right">
                  <Text className="item-input-text" decode={true}>
                    上传图片&ensp;
                  </Text>
                  <Image className="arrow-img" src={plus} />
                </View>
              </View>
            </>
          )}
          {/*附件图片列表*/}
          {enclosureList && enclosureList.length > 0 && <Enclosure storeId={supplier.storeId} />}

          {!isBookingSaleGoods && stores && stores.length > 1 && (
            <View className="order-confirm-store-item">
              <Text className="order-item-label">商品金额</Text>
              <View className="store-item-right">
                <Text className="item-text">¥{actions._addZero(tradePrice.goodsPrice)}</Text>
              </View>
            </View>
          )}

          {!isBookingSaleGoods && stores && stores.length > 1 && (
            <View className="order-confirm-store-item">
              <Text className="order-item-label">配送费用</Text>
              <View className="store-item-right">
                <Text className="item-text">¥{actions._addZero(tradePrice.deliveryPrice)}</Text>
              </View>
            </View>
          )}
        </View>
        {virtualGoods && (
          <Text style={{
            fontSize: '12px',
            color: "#999",
            marginTop: "10px",
            marginLeft: '12px'
          }}>
            * 请仔细阅读商品详情页中“须知”内容，购买后视为已阅读
          </Text>
        )}
      </>
    );
  }

  private listenKeyBordHidden = (enclosures, supplier) => {
    setTimeout(async () => {
      await this._chooseImage(enclosures, supplier.storeId);
    }, 500);
  };

  _chooseImage = async (enclosures, storeId) => {
    if (enclosures && enclosures[storeId] && enclosures[storeId].length === 10) {
      await Taro.showToast({
        title: '最多上传10张哦~',
        icon: 'none',
        duration: 1000,
      });
      return;
    }
    await this.props.actions.action._chooseImage(storeId);
  };

  /**
   * 去重
   * @param marketings
   */
  _distinct = (marketings) => {
    let newMarketings = [marketings[0]];
    marketings.map((marketing) => {
      let m = newMarketings.find((newMarketing) => newMarketing && newMarketing.marketingId == marketing.marketingId);
      if (!m) {
        newMarketings.push(marketing);
      }
    });
    return newMarketings;
  };
}

//create by moon https://github.com/creasy2010/moon
